import json
from django_celery_beat.models import PeriodicTask, IntervalSchedule


class MonitorDeviceTask(object):
    """
    设备创建，增加周期性任务
    """

    def __init__(self, ip):
        schedule, created = IntervalSchedule.objects.get_or_create(
            every=2,
            period=IntervalSchedule.SECONDS
        )
        self.periodic_task = PeriodicTask.objects.create(
            interval=schedule,
            name='Celery周期测试',
            task='periodic_task.tasks.monitor_device_task',
            args=json.dumps([ip])
        )

    def start(self):
        """
        启动任务
        """
        self.periodic_task.enabled = True
        self.periodic_task.save()

    def stop(self):
        """
        停止任务
        """
        self.periodic_task.enabled = False
        self.periodic_task.save()
